<template>
  <div class="column">
    <div class="col-1 row content-center q-pa-sm">
      <q-btn
        no-caps
        class="q-my-sm"
        :class="ui.btnClass"
        icon="add"
        :label="$t('mapIndex.地图创建')"
        @click="mapCreate"
      />
      <q-space></q-space>
      <q-input
        borderless
        v-model="searchText"
        :placeholder="$t('mapIndex.查询地图')"
        :dark="ui.isDark"
      >
        <template v-slot:append>
          <q-icon
            name="close"
            @click="searchText = ''"
            class="cursor-pointer"
            v-show="searchText"
          />
          <q-icon name="search" v-show="!searchText"/>
        </template>
      </q-input>
    </div>
    <!--地图列表-->
    <q-scroll-area
      :dark="ui.isDark"
      class="col-11 full-width"
      v-if="mapList.length"
    >
      <div class="full-height full-width row">
        <template v-for="(item, index) in mapList" :key="index">
          <div
            class="q-px-sm q-pb-md col-xs-12 col-sm-6 col-md-4 col-lg-3"
            v-show="item.name.includes(searchText)"
          >
            <!--地图卡片-->
            <q-card
              :dark="ui.isDark"
              :style="
                status.mapID === item.id
                  ? ui.isDark
                    ? 'border: 2px solid #F9A825'
                    : 'border: 2px solid #00C853'
                  : ''
              "
            >
              <!--卡片头-->
              <q-card-section
                class="row content-center"
                style="height: 50px; line-height: 50px"
              >
                <!--左上角当前地图与切换按钮-->
                <div class="col-3 text-left">
                  <template v-if="isConnected">
                    <q-chip
                      outline
                      class="text-space text-bold"
                      :label="$t('mapIndex.已选')"
                      :color="ui.isDark ? 'yellow-9' : 'green-14'"
                      icon="bookmark"
                      v-if="status.mapID === item.id"
                    />
                    <q-btn
                      no-caps
                      :class="ui.btnClass"
                      :label="$t('mapIndex.切换')"
                      @click="chooseMap(item)"
                      v-else
                    />
                  </template>
                </div>
                <!--地图名-->
                <strong
                  class="col-6 text-h6 text-center text-over"
                  style="height: 50px; line-height: 50px"
                >
                  {{ item.name }}
                </strong>
                <!--右上角更多按钮-->
                <div class="col-3 text-right">
                  <q-btn
                    no-caps
                    flat
                    rounded
                    :color="ui.isDark ? 'white' : 'black'"
                    icon-right="more_vert"
                    style="transform: translateX(25%)"
                  >
                    <q-menu
                      :dark="ui.isDark"
                      transition-show="jump-down"
                      transition-hide="jump-up"
                    >
                      <q-list style="min-width: 120px; letter-spacing: 2px">
                        <q-item
                          clickable
                          v-close-popup
                          @click="alterMap.show(item)"
                        >
                          <q-item-section>
                            <q-icon name="edit" size="sm" color="primary"/>
                          </q-item-section>
                          <q-item-section>
                            {{ $t("mapIndex.编辑") }}
                          </q-item-section>
                        </q-item>
                        <q-item
                          clickable
                          v-close-popup
                          @click="mapDelete(item)"
                        >
                          <q-item-section>
                            <q-icon name="delete" size="sm" color="negative"/>
                          </q-item-section>
                          <q-item-section>
                            {{ $t("mapIndex.删除") }}
                          </q-item-section>
                        </q-item>
                      </q-list>
                    </q-menu>
                  </q-btn>
                </div>
              </q-card-section>
              <!--分割线-->
              <q-separator :dark="ui.isDark" inset/>
              <!--图片部分-->
              <q-card-section>
                <q-img
                  class="cursor-pointer"
                  :ratio="16 / 9"
                  fit="cover"
                  @click="enterMap(item)"
                  :id="'img' + index"
                  :src="'data:image/png;base64,' + item.mapBase64"
                >
                  <!--                <q-img-->
                  <!--                  class="cursor-pointer"-->
                  <!--                  :ratio="16 / 9"-->
                  <!--                  fit="cover"-->
                  <!--                  @click="enterMap(item)"-->
                  <!--                  :id="'img' + index"-->
                  <!--                  :src="`${useAPIStore().mapUrl}new/map/download/${item.id}`"-->
                  <!--                >-->
                  <div
                    class="absolute-bottom text-subtitle1 text-center text-space"
                  >
                    {{ $t("mapIndex.点击进入") }}
                  </div>
                  <template v-slot:error>
                    <div
                      class="absolute-full flex flex-center bg-negative text-white"
                    >
                      Cannot load image
                    </div>
                  </template>
                </q-img>
              </q-card-section>
            </q-card>
          </div>
        </template>
      </div>
    </q-scroll-area>
    <!--地图列表为空-->
    <div class="col-11 relative-position" v-else>
      <div
        class="absolute-center orientation-landscape text-h3"
        :class="ui.isDark ? 'text-grey-4' : 'text-grey-8'"
        style="letter-spacing: 10px"
      >
        {{
          mapNotice === "searching"
            ? $t("mapIndex.正在获取地图列表")
            : mapNotice === "failed"
              ? $t("mapIndex.获取地图列表失败")
              : $t("mapIndex.地图列表当前为空")
        }}
      </div>
      <div
        class="absolute-center orientation-portrait text-h3"
        :class="ui.isDark ? 'text-grey-4' : 'text-grey-8'"
        style="letter-spacing: 10px"
      >
        {{
          mapNotice === "searching"
            ? $t("mapIndex.正在获取")
            : mapNotice === "failed"
              ? $t("mapIndex.获取地图")
              : $t("mapIndex.地图列表")
        }}
        <div style="height: 10px"></div>
        {{
          mapNotice === "searching"
            ? $t("mapIndex.地图列表")
            : mapNotice === "failed"
              ? $t("mapIndex.列表失败")
              : $t("mapIndex.当前为空")
        }}
      </div>
    </div>
    <q-inner-loading :showing="loading">
      <q-spinner-gears size="50px" color="primary"/>
      <q-btn
        no-caps
        flat
        color="primary"
        :label="$t('mapIndex.取消')"
        class="q-ma-lg"
        @click="loading = false"
      />
    </q-inner-loading>
    <modify-map ref="alterMap" @getMapList="getMapList"/>
  </div>
</template>

<script setup>
import {onMounted, ref, nextTick, watch, computed} from "vue";
import {api} from "boot/axios";
import {useAPIStore} from "stores/api";
import {useUiStore} from "stores/ui";
import {useQuasar} from "quasar";
import {useRouter} from "vue-router";
import {isConnected, status} from "src/utils/deviceWs";
import ModifyMap from "components/map/ModifyMap.vue";
import {useI18n} from "vue-i18n";

const t = useI18n().t;
const ui = useUiStore();
const $q = useQuasar();
const router = useRouter();

const loading = ref(false); //  loading效果显示
const searchText = ref(""); //  地图查询关键字
// const mapSelected = computed(() => status.value.mapID); //  设备当前地图ID
const mapList = ref([]); // 地图列表（选中地图优先的列表）
const mapListOrg = ref([]); // 接口返回的原始地图列表
const mapNotice = ref("");
const alterMap = ref();

// ------生命周期----------------------------------------------------------------------
onMounted(() => {
  getMapList();
});

// 渲染完后清除image对象
// nextTick(() => {
//   for (let i = 0; i < mapList.value.length; i++) {
//     window.URL.revokeObjectURL(document.getElementById("img" + (i + 1)).src);
//   }
// });

// ------监听-------------------------------------------------------------------------
// 监听当前地图
watch(() => status.value.mapID, () => {
  showMapSelected();
});

// ------事件函数----------------------------------------------------------------------
// 查询地图列表
function getMapList() {
  loading.value = true;
  mapNotice.value = "searching";
  api
    .get(useAPIStore().mapUrl + "map/all")
    // .get(useAPIStore().mapUrl + "new/map/all/simple")
    .then((res) => {
      // if (res.data.code === 200) {
      //   loading.value = false;
      //   mapListOrg.value = res.data.data;
      //   showMapSelected();
      //   mapNotice.value = "";
      // } else {
      //   loading.value = false;
      //   mapNotice.value = "failed";
      // }
      loading.value = false;
      mapListOrg.value = res.data;
      showMapSelected();
      mapNotice.value = "";
    })
    .catch((e) => {
      loading.value = false;
      mapNotice.value = "failed";
    });
}

// 将选中地图优先显示
function showMapSelected() {
  // 将顺序调整过的列表重置
  mapList.value = [...mapListOrg.value];
  // 有已选且list不为空
  if (!status.value.mapID || !mapList.value.length) return;

  const index = mapList.value.findIndex(item => item.id === status.value.mapID);
  const obj = index !== -1 && mapList.value.splice(index, 1)[0];
  obj && mapList.value.unshift(obj)
}

// 选择地图
function chooseMap(map) {
  $q.dialog({
    dark: useUiStore().isDark,
    title: t("mapIndex.切换地图"),
    message:
      `<span class="text-space">${t("mapIndex.是否将")}` +
      map.name +
      `${t("mapIndex.设为当前地图")}</span>`,
    html: true,
    ok: t("ok"),
    cancel: t("cancel"),
  }).onOk(() => {
    loading.value = true;
    api
      .get(useAPIStore().amrUrl + "map/set/" + map.id)
      .then((res) => {
        if (res.data) {
          $q.notify({
            message: t("mapIndex.切换地图成功"),
            color: "positive",
          });
        } else {
          $q.notify({
            message: `Failed:${t("mapIndex.切换地图失败")}`,
            color: "negative",
          });
        }
        loading.value = false;
      })
      .catch(() => {
        $q.notify({
          message: `Error:${t("mapIndex.切换地图失败")}`,
          color: "negative",
        });
        loading.value = false;
      });
  });
}

// 进入地图
function enterMap(map) {
  router.push({
    path: "/mapEdit",
    query: {id: map.id, title: t("mapIndex.地图") + "-" + map.name},
  });
}

// 创建地图
function mapCreate() {
  if (!isConnected.value) {
    $q.dialog({
      dark: ui.isDark,
      message: `<span class="text-space">${t(
        "mapIndex.设备未连接无法创建地图"
      )}</span>`,
      html: true,
      ok: t("mapIndex.知道了"),
    });
  } else {
    router.push("mapCreate");
  }
}

// 删除地图
function mapDelete(map) {
  $q.dialog({
    dark: ui.isDark,
    title: t("mapIndex.是否删除地图") + "-" + map.name,
    ok: t("ok"),
    cancel: t("cancel"),
  }).onOk(() => {
    api.delete(useAPIStore().mapUrl + "map/" + map.id).then(() => {
      $q.notify({
        message: t("mapIndex.删除地图成功"),
        color: "positive",
      });
      getMapList();
    });
  });
}
</script>

<style scoped></style>
